package cn.tedu.order.service;

import cn.tedu.order.entity.Order;
import cn.tedu.order.feign.AccountClient;
import cn.tedu.order.feign.EasyIdClient;
import cn.tedu.order.feign.StorageClient;
import cn.tedu.order.mapper.OrderMapper;
import cn.tedu.order.tx.OrderTccAction;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Random;

/**
 * @author Amos
 * @date 2022/4/23
 */

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private AccountClient accountClient;
    @Autowired
    private StorageClient storageClient;
    @Autowired
    private EasyIdClient easyIdClient;
    @Autowired
    private OrderTccAction tcc;

    @GlobalTransactional
    @Override
    public void create(Order order) {
        // 远程调用"全局唯一id发号器"，获得订单id
        Map<String, String> map = easyIdClient.nextId("order_business");
        Long orderId = Long.valueOf(map.get("data"));

        order.setId(orderId);

        // 正常执行创建订单业务
//        orderMapper.create(order);
        // 调用 TccAction 第一阶段方法，冻结订单
        /*
        对null的解释，tcc对象不是原始对象，是动态代理对象，用AOP切入的前置代码，
        在前置代码中会新建上下文对象传入原始方法
         */
        tcc.prepare(null,
                order.getId(),
                order.getUserId(),
                order.getProductId(),
                order.getCount(),
                order.getMoney());


        // 添加seata依赖但没有配置，后面两个模块不能启动，暂时不调用后面两个模块
        // 远程调用库存，减少库存
        storageClient.decrease(order.getProductId(), order.getCount());
        // 远程调用账户，扣减金额
        accountClient.decrease(order.getUserId(), order.getMoney());
    }
}
